package com.android.lovely.ui.activity

import android.os.Bundle
import android.text.Html
import android.text.method.LinkMovementMethod
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.android.lovely.api.service.userService
import com.android.lovely.data.SysMsg
import com.android.lovely.databinding.ActivityMsgBinding
import com.android.lovely.ext.windowBackgroundNav
import com.android.lovely.ext.windowBackgroundStatus
import com.android.lovely.framework.BaseActivity
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable

class MsgActivity : BaseActivity<ActivityMsgBinding>() {

    private val push: SysMsg? by lazy { intent.getParcelableExtra("msg") }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.back.clickable { onBackPressedDispatcher.onBackPressed() }
        mBinding.flTop.addStatusBarMarginTop()
        push?.let { inputContent(it) }
    }

    private fun inputContent(msg: SysMsg) {
        mBinding.title.text = msg.title
        mBinding.time.text = msg.time
        mBinding.selfQuestion.text = msg.reportContent
        updateAnswer(msg.content)
        mBinding.questionBody.isVisible = msg.reportContent.isNotEmpty()
        lifecycleScope.launchSafety {
            userService.getSystemPushDetail(mapOf("id" to msg.id))
        }
    }

    private fun updateAnswer(text: String) {
        val formattedText = text
            .replace(Regex("\\[(https?://[\\w./-]+)]")) { matchResult ->
                val url = matchResult.value.removeSurrounding("[", "]")
                "<a href=\"$url\" style=\"color:#5FB2FF;\">$url</a>"
            }
            .replace("\r\n", "<br>")
        mBinding.answerContent.text = Html.fromHtml(formattedText, Html.FROM_HTML_MODE_LEGACY)
        mBinding.answerContent.movementMethod = LinkMovementMethod.getInstance()
    }
}